package basemod

import (
	"time"
	"runtime/debug"
	
	"gitee.com/wint/tge/log"
)

// 基础模块基类
type BaseMod struct {
	NetDataProcessing

	rc 		chan IMsgPack
	fc 		chan func()
}

func (m *BaseMod) Init() {
}

func (m *BaseMod) Run(closeSig chan bool) {
	m.rc = make(chan IMsgPack, 1024)
	m.fc = make(chan func(), 1024)

	dt := 100 * time.Millisecond
	tick := time.Tick(dt)

	var updater IUpdater
	if nil != m.Impl {
		if v, ok := m.Impl.(IUpdater); ok {
			updater = v
		}
	}
	for {
		select {
		case <- tick:
			if nil != updater {
				updater.Update(dt)
			}
		case msg, ok := <- m.rc:
			if !ok {
				// break
			} else {
				code := m.DoMsg(msg)
				if 0 != code {
					msg.GetSes().Send(&Err{msg.GetMsg().GetProtoId(), code, ""})
				}
			}
		case fn, ok := <- m.fc:
			if !ok {
				// break
			} else {
				m.excuteFn(fn)
			}
		case <- closeSig:
			return
		}
	}
}

func (m *BaseMod) Destroy() {
	close(m.rc)
	close(m.fc)
}

func (m *BaseMod) OnRecv(pack IMsgPack) {
	defer func() {
		if err := recover(); err != nil {
			log.Print("BaseMod ERROR: ", err, string(debug.Stack()))
		}
	} ()
	
	if len(m.rc) < 1024 {
		m.rc <- pack
	}

	// code := m.DoMsg(pack)
	// if 0 != code {
	// 	pack.Send(&Err{pack.GetMsg().GetProtoId(), code, ""})
	// }
}

// 响应回调函数
func (m *BaseMod) OnFunc(fn func()) {
	defer func() {
		if err := recover(); err != nil {
			log.Print("NetRecver ERROR: ", err)
		}
	} ()
	
	if len(m.fc) < 1024 {
		m.fc <- fn
	}
}

func (m *BaseMod) excuteFn(fn func()) {
	defer func() {
		if err := recover(); err != nil {
			log.Print("NetRecver ERROR: ", err)
		}
	} ()

	fn()
}